import { getCurrentWindow } from "@tauri-apps/api/window";
import { WebviewWindow } from "@tauri-apps/api/webviewWindow";

export function useWindowManager() {
  const currentWindow = getCurrentWindow();

  /**
   * 切换到悬浮窗口
   */
  async function switchToFloating() {
    try {
      // 获取或创建悬浮窗口
      let floatingWindow = await WebviewWindow.getByLabel("floating");

      if (!floatingWindow) {
        // 如果悬浮窗口不存在，创建它
        floatingWindow = await new WebviewWindow("floating", {
          url: "/",
          title: "悬浮便签",
          width: 320,
          height: 480,
          resizable: true,
          decorations: false,
          transparent: true,
          alwaysOnTop: true,
          skipTaskbar: true,
        });

        // 等待窗口创建完成
        if (floatingWindow) {
          await new Promise((resolve) => {
            floatingWindow?.once("tauri://created", resolve);
          });
        }
      }

      // 显示悬浮窗口并聚焦
      if (floatingWindow) {
        await floatingWindow.show();
        await floatingWindow.setFocus();
      }

      // 隐藏当前主窗口
      await currentWindow.hide();
    } catch (error) {
      console.error("Failed to switch to floating window:", error);
    }
  }

  /**
   * 切换到主窗口
   */
  async function switchToMain() {
    try {
      const mainWindow = await WebviewWindow.getByLabel("main");
      if (mainWindow) {
        await mainWindow.show();
        await mainWindow.setFocus();

        // 隐藏当前窗口
        await currentWindow.hide();
      }
    } catch (error) {
      console.error("Failed to switch to main window:", error);
    }
  }

  /**
   * 获取当前窗口标签
   */
  async function getCurrentLabel() {
    return currentWindow.label;
  }

  return {
    switchToFloating,
    switchToMain,
    getCurrentLabel,
  };
}
